package com.demo.connectdbtest.module.ssh.controller;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SCPInputStream;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;

@RestController
@RequestMapping("/tarTest")
public class TarTest {

    @GetMapping("/down")
    public String down() throws IOException {
        // 远程机器ip
        String ip = "10.252.176.46";
        // ssh端口
        int port = 22;
        // ssh登录 用户名 密码
        String pwd = "Anjian@20230411^";
        String user = "root";
        String system = "passenger";
        String jarName = "passenger-management-bootstrap-V3.1.3.113.jar";
//        String jarName = "passenger-management-bootstrap-3.1.2-SNAPSHOT.jar";
        String dowloadJarPath = "/data/project/security-check/jar-file/" + jarName;
        String storageDir = "/data/testClasses/";
        String storagePath = storageDir + system + File.separator;
        String storageJarPath = storagePath + jarName;
        File storageFile = new File(storagePath);
        File storageFileDir = new File(storageDir);
        if (!storageFileDir.exists()) {
            storageFileDir.mkdirs();
        }
        if (!storageFile.exists()) {
            storageFile.mkdirs();
        }

        // 创建链接
        Connection conn = new Connection(ip, port);
        conn.connect();
        // 登录
        conn.authenticateWithPassword(user, pwd);

        // 获取SCPClient
        SCPClient sc = conn.createSCPClient();
        // 获取远程机器上的文件流 (远程文件地址的绝对路径)
        SCPInputStream is = sc.get(dowloadJarPath);
        // 创建本机文件写入流
        FileOutputStream os = new FileOutputStream(new File(storageJarPath));
        // 将文件写入本地
        byte[] b = new byte[4096];
        int i;
        while ((i = is.read(b)) != -1) {
            os.write(b, 0, i);
        }
        os.flush();
        // copy完成，关闭相应资源
        is.close();
        os.close();
        conn.close();
        System.out.println("copy ok");
        //原文链接：https://blog.csdn.net/TutinBing/article/details/95726639

        //NEW进行本地的字节码解压操作
        String uncompressPath = "/data/uncompressClasses/";
        File uncompressFile = new File(uncompressPath);
        if (!uncompressFile.exists()) {
            uncompressFile.mkdirs();
        }

        String path = storagePath;

        String jarPath = storageJarPath;
        //StringBuilder cmd = new StringBuilder();
        String[] cmd = {"/bin/sh", "-c", "cd " + path + ";jar -xvf " + jarPath};
        if (File.separator.equals("\\")) {
            //cmd.append("cmd /c cd " + path + " && jar -xvf " + jarPath);
            System.out.println("执行命令cmd : " + cmd);
        } else {
            // cmd.append("/bin/sh -c cd " + path + " && jar -xvf " + jarPath);
            //String[] cmd = {"/bin/sh", "-c", "cd" + path + ";jar -xvf" + jarPath};
            System.out.println("执行命令/bin/sh : " + cmd);
        }
        //Process exec = Runtime.getRuntime().exec(String.valueOf(cmd));
        Process exec = Runtime.getRuntime().exec(cmd);

        //输出是为了解决卡住问题
        InputStream in = exec.getInputStream();
        InputStreamReader inReader = new InputStreamReader(in);
        BufferedReader inBr = new BufferedReader(inReader);
        String strIn;
        while ((strIn = inBr.readLine()) != null) {
            System.out.println(strIn);
        }

        FileUtils.copyDirectoryToDirectory(new File(path + "/BOOT-INF/classes/com"), new File(path));


        //true 代表递归 false 代表不递归
        Collection<File> files = FileUtils.listFiles(new File(path + "BOOT-INF/lib/"), null, false);
        //StringBuilder executeCmd = new StringBuilder();
        //executeCmd.append("/bin/sh -c cd " + path);
        StringBuilder jarPartCommand = new StringBuilder();
        for (File file : files) {
            System.out.println(file.getName());
            if (file.getName().contains("passenger")) {
                FileUtils.copyFileToDirectory(file, new File(path));
                // executeCmd.append(";jar -xvf " + path + "/" + file.getName());
                jarPartCommand.append(";jar -xvf " + path + "/" + file.getName());
            }
        }
        String[] executeCmd = {"/bin/sh", "-c", " cd " + path + jarPartCommand};
        System.out.println("executeCmd命令：" + executeCmd.toString());
        Process result = Runtime.getRuntime().exec(executeCmd);
        System.out.println(result);
        System.out.println(exec);
        //复制字节码文件到其他的地方
        FileUtils.copyDirectoryToDirectory(new File(path + "com"), new File(uncompressPath + system + "/"));


        //操作完成后删除解压的文件
        String[] list = storageFileDir.list();
        //递归删除目录中的子目录下
        for (String name : list) {
            delete(new File(storageFileDir, name));
        }
        // 最外面的文件夹此时为空，可以删除
        storageFileDir.delete();
        System.out.println("递归删除文件完成");
        return "ok";
    }

    public static void delete(File file) {
        if (file.isDirectory()) {
            for (String sub : file.list()) {
                delete(new File(file, sub));
            }
            file.delete();
        }
        if (file.isFile()) {
            System.out.println("删除的文件：" + file.getName());
            // System.out.println(f.getAbsolutePath()+"是文件");
            file.delete();
        }
    }


}
